var Sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

/** 
 * 将form表单中的值转换为jsonString格式 
 */  
$.fn.form2JSONString = function() {
	return JSON.stringify(this.form2json());
};
/** 
 * 将form表单中的值转换为json格式 
 */  
$.fn.form2json = function() {
	var obj={};
    function evalThem (str) {
        var attributeName =  str.split("=")[0];
        var attributeValue = str.split("=")[1];
        if(!attributeValue){
            attributeValue = '';
        }
        var array = attributeName.split(".");  
        for (var i = 1; i < array.length; i++) {
            var tmpArray = Array();  
            tmpArray.push("obj");  
            for (var j = 0; j < i; j++) {
                tmpArray.push(array[j]);  
            };  
            var evalString = tmpArray.join(".");  
            if(!eval(evalString)){  
                eval(evalString+"={};");                  
            }  
        };  
        if(attributeName != null && "" != attributeName && "null" != attributeName){
        	obj[attributeName] = decodeURIComponent(attributeValue).replace(/'/, "\\'");
        }
    };
    var properties = this.serialize().replace(/\+/g," ").split("&");  
    for (var i = 0; i < properties.length; i++) {  
        evalThem(properties[i]);  
    };  
    return obj;  
};
/**
 * 关闭编辑行
 */
function endEditDatagrid(grid_id,fn){
	window.document.body.onclick = function(event){
		event = event || window.event;
		var target = event.srcElement || event.target;
		while(target.tagName != "BODY"){
			var field = $(target).attr("field");
			if(field != undefined){return;}//找到field就表示在点击行
			if(target.className == "page_1" ){break;}
			target = target.parentNode;
			if(target == null){return;}//目标都找不到,闪
		}
		$(grid_id).datagrid('endEdit', $(grid_id).datagrid('options').lastIndex);
		if (typeof (fn)=="function"){fn(grid_id);}
		return;//找到BODY层表示点击行以外的地方,就关闭编辑行
	};
}
String.prototype.trim=function (){
	return this.replace(/(^\s*)|(\s*$)/g, "");
};
/** 返回一个去掉首尾空格的数字 */
trimNumber=function (numStr){
	numStr = trimString(numStr);
	if(numStr==""){return 0;}
	else if(isNaN(parseFloat(numStr))){return 0;}
	else{return parseFloat(numStr);}
};
/** 返回一个去掉首尾空格的字符串 */
trimString=function (str){
	return (str==undefined || str==null) ? "" : (""+str).trim();
};
/** 
 * 合并两个json对象属性为一个对象 
 * @param j1 
 * @param j2 
 * @returns r 
 */  
//var mergeJsonObject = function(j1, j2){
//	var r={};
//	for(var attr in j1){
//		r[attr]=j1[attr];  
//	}
//	for(var attr in j2){  
//		r[attr]=j2[attr];  
//	}
//	return r;
//};
//提示信息
function alertPromptInfo(msg,fn){
	$.messager.alert('提示信息',msg,'info',fn);
}
function alertPrompt(msg,info,fn){
	$.messager.alert('提示信息',msg,info,fn);
}
var a = function(msg){
	alert(msg);
};
/** 
 * 合并两个json
 * @param des
 * @param src 
 * @returns des 
 */  
function extend(des, src, override){
	$.extend(des,src);//以后直接用这句,然后这段js删掉
    /*if(src instanceof Array){
    	for(var i = 0, len = src.length; i < len; i++)
    		extend(des, src[i], override);
    }
    for( var i in src){
        if(override || !(i in des)){
            des[i] = src[i];
        }
    }
	return des;*/
}
/** 无名方法待扩展(未完成,求完成~~) */
//$.fn.addJsonObject = function(jsonObject){
//	$.extend(this,jsonObject);
//};
/** 获得一个json对象 参数:条件对象,sql语句名,回调函数你懂的.*/
var getJsonObject=function(info,sSqlName,callback,sFormId){
	$.extend(info,$(trimString(sFormId)).form2json());//把form加进info对象里
	info["webUrl"]=window.location.href;
    return $.post("./wb/dynamicService_queryJSONObject.action",{"sjsonObject":JSON.stringify(info),"sqlName":sSqlName},'json');
};
/** 获得一个count 参数:条件对象,sql语句名,回调函数你懂的.*/
var getJsonCount=function(info,sSqlName,callback,sFormId){
	$.extend(info,$(trimString(sFormId)).form2json());//把form加进info对象里
	info["webUrl"]=window.location.href;
    return $.post("./wb/dynamicService_queryCount.action",{"sjsonObject":JSON.stringify(info),"sqlName":sSqlName},'json');
};
/** 获得一个json数组 参数:条件对象,sql语句名,回调函数你懂的.*/
var getJsonArray=function(info,sSqlName,callback,sFormId){
	$.extend(info,$(trimString(sFormId)).form2json());//把form加进info对象里
	info["webUrl"]=window.location.href;
	return $.post("./wb/dynamicService_queryJSONArray.action",{"sjsonObject":JSON.stringify(info),"sqlName":sSqlName},'json');
};
/** 载入页面form数据,参数:sOutFormId,info{["key":"value"]},sQueryFormId,sqlmap名 例:queryMyFormDataExample()*/
var loadFormData=function(sOutFormId,jform,sQueryFormId,sSqlName){
	$.extend(jform,$(sQueryFormId).form2json());//把form加进info对象里
	jform["webUrl"]=window.location.href;
	var sform = JSON.stringify(jform);//字符化form对象
    $.post("./wb/dynamicService_queryJSONObject.action",
	    {"sjsonObject":sform,"sqlName":sSqlName},
	    function(data) {
	    	$(sOutFormId).form('load',data);
		},'json'
    );
};
/** 这是一个例子:载入dataGrid数据*/
//var queryMyGridDataExample = function(){
//	loadGridData("#easyTable",{},"#fquery","RCYWBillD.queryStock");//1
//	loadGridData("#easyTable",{"bill_id":""},"","RCYWBillD.queryStock");//2
//}
/** 载入datagrid数据,参数:gridid,info{["key":"value"]},formid,sqlmap名 例:queryMyGridDataExample()*/
var loadGridData=function(sGridId,info,sQueryFormId,sSqlName){
	var jform={};
	if(trimString(sQueryFormId)!=""){jform=$(sQueryFormId).form2json();}
	var grid = $(sGridId);
	jform = $.extend(jform,info);
	jform["webUrl"]=window.location.href;
	var sform = JSON.stringify(jform);//字符化form对象
	grid.datagrid('options').queryParams = {"sjsonObject":sform,"sqlName":sSqlName};
	grid.datagrid('options').url = CONTEXT_PATH+"/wb/dynamicService_queryGridData.action";
	grid.datagrid('reload');
};
/** 获得一个json数组 用于评论查询*/
var getJsonArrayC=function(info,sSqlName){
	info["webUrl"]=window.location.href;
    return $.post("./wb/dynamicService_queryComments.action",{"sjsonObject":JSON.stringify(info),"sqlName":sSqlName},'json');
};
/** 打开一个新页面 */
//var openNewForm=function (page_name, para_list, is_maximum){
//	var load_time=new Date();
//	var load_label=page_name.replaceAll(".","").replaceAll("/","")+load_time.getTime();
//	para_list=trimString(para_list);
//	var url=CONTEXT_PATH+page_name;
//	if (para_list!="")url+="?"+para_list;
//	var openPara="toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=yes,scrollbars=yes,";
//	if (is_maximum==true){
//		openPara+="width="+(screen.availWidth-10)+",height="+(screen.availHeight-30)+",top=0,"+"left=0";
//	}else{
//		openPara+="width=900,height=600,top="+
//		((screen.availHeight-600)/2)+",left="+((screen.availWidth-900)/2);
//	}
//	return window.open(url, load_label, openPara);
//};
/** 替换换行符 */
//var replaceCR=function (str_value, replace_str){
//	if (!isAvailable(replace_str))
//	replace_str="??";
//	str_value=trimString(str_value);
//	var index=str_value.indexOf("\r\n");
//	while (index!=-1){
//		str_value=str_value.substring(0, index)+replace_str+str_value.substring(index+2);
//		index=str_value.indexOf("\r\n");
//	}
//	return str_value;
//}

//上个月的今天【粗略以30天计算】
var LAST_MONTH_TODAY = getDifferenceDay(30);
//当前日期
var TODAY = getToday();
//下个月的今天
var NEXT_MONTH_TODAY = getDifferenceDay(-30);
function getToday (){
   var n = new Date();
   var y = n.getFullYear();       //年
   var m = n.getMonth() + 1;     //月
   var d = n.getDate();            //日
   var c = y + "-";
   if(m < 10){c += "0";}
   c += m + "-";
   if(d < 10){c += "0";}
   c += d + "";
   return c; 
}

//获取与当前日期差额日期：取过去日期参数days为正数;获取未来时间，参数days为负数
function getDifferenceDay (days){	
   var now = new Date();
   var year = now.getFullYear();       //年
   var month = now.getMonth() + 1;     //月
   var day = now.getDate();            //日
   
   var newDate = new Date(year, month-1, day);
   var seconds = newDate-(24*60*60*1000*(days));
   var differenceDay = new Date();
   differenceDay.setTime(seconds);
   
   year = differenceDay.getFullYear();       //年
   month = differenceDay.getMonth() + 1;     //月
   day = differenceDay.getDate();            //日
   
   var clock = year + "-";
   if(month < 10){clock += "0";}
   clock += month + "-";
   if(day < 10){clock += "0";}
   clock += day + "";
   return clock; 
}
	
//当前时间    
var  getCurrentTime = function (){
   var n = new Date();
   var y = n.getFullYear();       //年
   var m = n.getMonth() + 1;     //月
   var d = n.getDate();            //日
   var hh = n.getHours();            //时
   var mm = n.getMinutes();          //分
   var ss=n.getSeconds();			  //秒
   var c = y + "-";
   if(m < 10){c += "0";}
   c += m + "-";
   if(d < 10){c += "0";}
   c += d + " ";
   if(hh < 10){c += "0";}
   c += hh + ":";
   if (mm < 10){c += '0';}
   c += mm; 
   c+=":"+ss;
   return c; 
};

/**
 * 调用后台函数,使用时用Communicator.send(),参数:类名,方法名,数据信息对象,回调函数对象,异步提交标记
 * 默认为异步提交,函数参数名前缀s为字符串,j为json对象,b为布尔类型
 */
var Communicator = {
	send : function (sService, sMethod, jInfo, jCallback, bAjaxMode){
		if (bAjaxMode!==false){bAjaxMode=true;}
		$.ajax({
			type : "POST", async : bAjaxMode, dataType : "json",
			url : "./wb/dynamicService_dynamicInvoke.action",
			data :{
				"sService" : sService, "sMethod" : sMethod, "sjsonObject" : JSON.stringify(jInfo)
			}, success : function (data){
				if ((typeof (jCallback)=="object") && (jCallback!=null)){
					if (typeof (jCallback.onSuccess)=="function"){jCallback.onSuccess(data);}
				}else{
					a(data.msg);
				}
			}, error : function (xmlR, status, e){
				if (typeof (jCallback)=="object"){
					if (typeof (jCallback.onFail)=="function"){jCallback.onFail(xmlR, status, e);}
				}else{
					a("["+sService+"."+sMethod+"]调用失败，原因["+xmlR.responseText+"]");
				}
			}
		});
	}
};
function strDateRegular(str){ 
	var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); 
	if(r==null)return false; 
	var d= new Date(r[1], r[3]-1, r[4]); 
	return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); 
} 
function strDateTimeRegular(str){ 
	var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; 
	var r = str.match(reg); 
	if(r==null)return false; 
	var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); 
	return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]); 
}
/** 全文检索替换字符, 参数:目标字符串,替换字符串,忽略大小写(默认不忽略)*/
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
        return this.replace(new RegExp(reallyDo, (ignoreCase===true ? "gi": "g")), replaceWith);  
    } else {  
        return this.replace(reallyDo, replaceWith);  
    }  
};

/**cookie start*/
/*创建cookie,days参数如为空则cookie永久有效*/
function createCookie(name, value, days) {
	var expires;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	} else{
		expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}
/*读取cookie值*/
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for ( var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length, c.length);
	}
	return null;
}
/*清空cookie*/
function eraseCookie(name) {
	createCookie(name, "", -1);
}
/**cookie end*/

/**
 * 文件上传方法
 * @param sFileElementId
 * @param jCallback
 * @returns
 */
var ajaxFileUpload = function(sFileElementId,jCallback){
  //检查上传文件扩展名
  var fileName = $("#"+sFileElementId).val();
  if ( trimString(fileName)=="") {
    alert("文件名不能为空");
    return;
  }
  var fileType = fileName.substring(fileName.lastIndexOf(".") +1);
  if (fileType != "xls" && fileType != "xlsx" && fileType != "doc" && fileType != "docx" && fileType != "pdf" && fileType != "jpg" && fileType != "png" && fileType != "bmp"&& fileType != "gif" && fileType != "tif" && fileType != "zip" && fileType != "rar"&&fileType != "igs"&&fileType != "tiff") {
    alert("文件上传发生错误！文件格式不正确");
    return;
  }
  $.cachedScript([CONTEXT_PATH+"/common/js/ajaxfileupload.min.js"],function(){
    $.ajaxFileUpload({
      url:'fileUploadAction.action',//用于文件上传的服务器端请求地址
            secureuri:false,//一般设置为false
            fileElementId:sFileElementId,//文件上传空间的id属性  <input type="file" id="file" name="file" />
            dataType: 'json',//返回值类型 一般设置为json
      success : function(data, ajaxStatus){
        var status = data.status;//上传状态
        //var msg = data.message;//返回信息
        //var filePath = data.filePath;//文件路径
        if((typeof (jCallback)=="object") && (jCallback!=null)){//判断有没有回调对象
          if(status && typeof (jCallback.onSuccess)=="function"){//判断对象有没有成功函数
            jCallback.onSuccess(data);
          }else if(!status && typeof (jCallback.onFail)=="function"){//判断对象有没有失败函数
            jCallback.onFail(msg);
          }
        }else{
          alert(msg);//无回调对象就直接弹出消息
        }
      },
      error : function(data, status, e){
        var rText = data.responseText;
        try {
          this.success(JSON.parse(rText));//解析返回的字符串(调用成功函数,统一处理)
        } catch (e) {
          alert("上传失败,请联系管理员.");//不可控异常
        }
      }
    });
  });
};
var log = function(obj) {
	var host = window.location.host;
	if (window.console && host!="api.baosaas.com") {
		console.log(obj);
	}
};
/*扩展函数,元素的外部html*/
$.fn.outerhtml = function(s) {
	return (s) ? this.before(s).remove() : $("<p>").append(this.eq(0).clone()).html();
};
/*把url转换为json对象*/
function url2Json(url) {
	if(!url){
		url = window.location.search;
	}
	url = url.substring(url.indexOf("?")+1, url.length);
	if(url == ""){
		return {};
	}
	var p = url.split('&')
	,j={};
	$.each(p,function (i, v) {
		var a = v.split("=");
		j[a[0]]=a[1];
	});
	return j;
}
/** 替换字符串内的html代码(目前只替换<>符号内的字符) */
replaceJsonCharacter=function (str_value, replace_str){
	var reg = /(\{([\w+$])*\})/;
	while (reg.test(str_value)){
		str_value = str_value.replaceAll(reg,"");
	}
	return str_value;
};
/*使非HTML5支持placeholder属性 */
var supportPlaceholder = {
	support : 'placeholder' in document.createElement('input'),
	init : function(){
		if(!supportPlaceholder.support){
			$("[placeholder]").each(function(){
				if($(this).val()==""){
					$(this).val($(this).attr("placeholder"));
				}
			});
		}
	},
	run : $(function(){
		if(!supportPlaceholder.support){
			supportPlaceholder.init();
			$("[placeholder]").die("focus").live("focus",function(){
				if ($(this).val() === $(this).attr("placeholder")) {
					$(this).val("");
		        }
			});
			$("[placeholder]").die("blur").live("blur",function(){
				if ($(this).val() === "") {
					$(this).val($(this).attr("placeholder"));
		        }
			});
		}
	})
};
/*var supportPlaceholder = {
		support : 'placeholder' in document.createElement('input'),
		init : function(){
			if(!supportPlaceholder.support){
				$("[placeholder]").each(function(){
					if($(this).val()==""&&$(this).siblings(".placeholder").size()==0){
						var lb = $("<label name='placeholder'>").addClass("placeholder")
						.text($(this).attr("placeholder"));
						lb.css("top",$(this).position().top+'px');
						lb.css("left",$(this).position().left+'px');
						lb.css("line-height",$(this).css("line-height"));
						lb.insertAfter($(this));
						lb.click(function(){
							$(this).prev().focus();
						});
					}
				});
			}
		},
		run : $(function(){
			if(!supportPlaceholder.support){
				supportPlaceholder.init();
				$("[placeholder]").die("input propertychange").live("input propertychange",function(){
					$(this).siblings(".placeholder").hide();
				});
				$("[placeholder]").die("keyup").live("keyup",function(){
					if ($(this).val() === "") {
						$(this).siblings(".placeholder").show();
					}else{
						$(this).siblings(".placeholder").hide();
					}
				});
			}
		})
	};*/
/*iframe自适应高度*/
function dyniframesize(iframe) {
	var height= 600;
	if (Sys.ie || Sys.firefox || Sys.opera) {
		height = iframe.contentWindow.document.body.scrollHeight;
	} else if (Sys.chrome || Sys.safari) {
		height = iframe.contentWindow.document.documentElement.scrollHeight;
	}
	if (Sys.ie) {
		iframe.style.height = height;
		iframe.height = height;
	} else {
		iframe.height = height;
	}
};

/*当日供销存上传begin.............*/
var dailyUpload = function(obj,t,l,ft){	
	$.cachedCss([[CONTEXT_PATH,"/common/js/jquery-easyui-1.2.5/themes/gray/easyui.css"].join("")],  function(){
		$.cachedScript([[CONTEXT_PATH,"/common/js/jquery-easyui-1.2.5/jquery.easyui.min.js"].join(""),
						[CONTEXT_PATH,"/common/js/jquery-easyui-1.2.5/locale/easyui-lang-zh_CN.js"].join("")],  function() {
			$("#updialog").closest("div.panel").remove();
			var dialoghtml = ['<div id="updialog" name="dialog">',
							  '<table>',
							  '<tr>',
							  '<td width="20">',
							  '</td>',
							  '<td>',
							  '<a class="btn adddingdan" onclick="saveUpload(\'',ft,'\'); " >上传</a>',
							  '</td>',	
							  '</tr>',	
							  '<tr height="10">',	
							  '</tr>',	
							  '<tr>',	
							  '<td width="20">',
							  '</td>',
							  	'<td >',						  		
									'<input type="file" id="file" name="file" size="45" height="20"  style="height:22px">',
								'</td>',
							  '</tr>',
							 '</table>',			  
							 '</div>'].join("");
			$(document.body).append(dialoghtml);
			if(!t) t=0; 
			if(!l) l=0; 
			var top = $(obj).offset().top-t;
			var left = $(obj).offset().left-l;
		    $("#updialog").dialog({
		    	"left":left,
		    	"top":top,
		    	doSize:true,
		        draggable: true,
		        resizable: false,
		        shadow: false,
		        closed:true,
		        title:"上传",
		        show: 'Transfer',
		        hide: 'Transfer',
		        autoOpen: false,
		        width:400,
		        height:150, 
		        minHeight: 100, 
		        minwidth: 10
		    });
			$("#updialog").dialog("open");
		});
	});
};
/*上传文件*/
var saveUpload=function(sFileElementId,ft,callCheck){
	//检查上传文件扩展名
	var fileName = $("#"+sFileElementId).val();
	if ( trimString(fileName)=="") {
		alertPrompt("文件名不能为空","info");
		return;
	}
	var fileType = fileName.substring(fileName.lastIndexOf(".") +1);
	if (ft=="jpg"){
		if (fileType.toLocaleLowerCase() != "bmp" && fileType.toLocaleLowerCase() != "tif" &&fileType.toLocaleLowerCase() != "jpg" && fileType.toLocaleLowerCase() != "png" && fileType.toLocaleLowerCase() != "gif") {
			alertPrompt("文件上传发生错误！文件格式不正确 请上传图片","info");
			return;
		}
	}
	if (ft=="pdf"){
		if (fileType != "pdf"){
			alertPrompt("文件上传发生错误！文件格式不正确 请上传pdf文件!","info");
			return;
		}
	}
	if (ft=="xls"){
		if (fileType != "xls" && fileType != "xlsx") {
			alertPrompt("文件上传发生错误！文件格式不正确 请上传excel(.xls或.xlsx)文件!","info");
			return;
		}
	}
	
	if (fileType.toLocaleLowerCase() == "exe" ) {
		alertPrompt("文件上传发生错误！非法文件格式！","info");
		return;
	}
	//$.messager.progress({msg:'正在上传...',text:'请稍候'});
	ajaxFileUpload(sFileElementId,{
		onSuccess : 
	   		function(data){
	   			if ((typeof (callCheck)=="object") && (callCheck!=null)){
					if (typeof (callCheck.onSuccess)=="function"){callCheck.onSuccess(data);}
	   			}else{
	   				//$.messager.progress('close');
		   			alertPrompt(data.message,"info");
		   			$("#uploadfilepath").val(data.filePath);
		   			$("#updialog").dialog("close");
	   			}
			},
	 		onFail: function(sMsg) {$.messager.progress('close');
	 				a(sMsg);
	 		}
	});
};

/*当日供销存上传end.............*/

$(function() {
	/* 初始化记录已在页面标签引入的脚本 */
	$("script").each(function(i) {
		var name = this.src.substring(this.src.indexOf(CONTEXT_PATH) + 5, this.src.length);
		scriptsJsonSet[name] = 1;
	});
});
/* 用来标记是否某个script已经下载到本地 */
var scriptsJsonSet = {};
$.cachedCss = function(urlArray, method) {
	var len = urlArray.length;
	for ( var i = 0; i < len; i++) {
		var url = urlArray[i];
		if ($("[href='" + url + "']").size() == 0) {
			var styleTag = document.createElement("link");
			styleTag.setAttribute('type', 'text/css');
			styleTag.setAttribute('rel', 'stylesheet');
			styleTag.setAttribute('href', url);
			$("head")[0].appendChild(styleTag);
			log("成功！" + url);
		}
	}
	if (typeof method == "function") {
		method();
	}
};
/* 载入脚本实现方法,也可调用 */
$.cachedScript = function(urlArray,method,async,cache) {
	var len = urlArray.length;
	var idx = 0;
	getScript(urlArray);
	function getScript(urlArray) {
		if (len == idx) {
			if (typeof method == "function") {
				method();
			}
			return;
		}
		var casheUrlKey = urlArray[idx];
		casheUrlKey = casheUrlKey.substring(casheUrlKey.indexOf(CONTEXT_PATH + "/"), casheUrlKey.length);
		casheUrlKey = casheUrlKey.replace(CONTEXT_PATH, "");
		casheUrlKey = casheUrlKey.substring(casheUrlKey.indexOf("./") + 1, casheUrlKey.length);

		cachedScript(urlArray[idx]).done(function() {
			if(scriptsJsonSet[casheUrlKey] != 1){
				log("成功！" + casheUrlKey);
			}else{
				log("取缓：" + casheUrlKey);
			}
			scriptsJsonSet[casheUrlKey] = 1;
			idx++;
			getScript(urlArray);
		}).fail(function() {
			log("失败了！" + casheUrlKey);
			idx++;
			getScript(urlArray);
		});

		function cachedScript(url) {
			if (!scriptsJsonSet[casheUrlKey]) {
				cache = (cache==undefined)?(JSCACHE==undefined?false:JSCACHE):cache;
				var options = {
					cache : cache,
					async : async==undefined?true:async,
					dataType : "script",
					url : url
				};
				return $.ajax(options);
			} else {
				return $.ajax();
			}
		}
	}
};
/*文字处理,当描述的长度大于传入的长度时变为...*/
var getDesc = function(desc,len){
	if (trimString(desc).length>len){
		return desc.substring(0,len)+"...";
	}
	return desc;
};
/*默认图片*/
var defaultface = function(e){
	var img = e.target;
	if(img && typeof $(img).attr("face") != "undefined"){
		$(img).attr("src","./images/face.gif");
		img.onerror=null;
		$(img).unbind("error");
	}else{
		$(img).replaceWith("<p><b>图片未加载！</b></p>");
	}
};
/*默认图片*/
var defaultpic = function(){
	var img = event.srcElement ? event.srcElement : event.target;
	$(img).attr("src","./images/nopicture.gif");
	img.onerror=null;
	$(img).unbind("error");
};
/**
 * 遮罩层
 */
$.shade = {
	init:function($target,options){
		var opts = $.extend({}, $.shade.defaults, options);
		$target=!$target?$("body"):$target;
		var $html = $('<div class="shade"></div>');
		if(opts.progressbarstyle>0){
			$html.append(opts.progressbar[opts.progressbarstyle]);
		}
		var top = opts.top?opts.top:$target.offset().top
		,left = opts.left?opts.left:$target.offset().left
		,width = opts.width?opts.width:$target.width()
		,height = opts.height?opts.height:$target.height();
		$html.css("top",top).css("left",left).css("width",width).css("height",height);
		$target.append($html);
		if(opts.progressbarstyle==2){
			var $img =$target.find("div.shade .slider");
			if($img.size() > 0){
				$.shade.interval($img);
			}
		}
	},
	defaults:{
		"top":null,
		"left":null,
		"width":null,
		"height":null,
		"progressbarstyle":2,
		"progressbar":["","<img src='{CONTEXT_PATH}/common/image/loading/08.gif'></img>",
		                    "<div class=progress><div class=slider></div></div>"],
		"patch":$(function(){
			$.shade.defaults.progressbar[1]=$.shade.defaults.progressbar[1].replace("{CONTEXT_PATH}",CONTEXT_PATH); 
		})
	},
	interval:function($img){
		var $p = $img.parent();
		var offset = 10;
		slidertime = window.setInterval(function(){
			var left = trimNumber($img.css("left"));
			var width = trimNumber($img.css("width"));
			var pwidth = trimNumber($p.css("width"));
			var newleft = left+offset;
			if(left==0&&width < 30){
				width+=offset;
				$img.css("width",width+"px");
				return;
			}else if(newleft+width > pwidth){
				width-=offset;
				if(width <= 0){
					newleft=0;
					width=10;
				}
			}
			$img.css("left",newleft+"px");
			$img.css("width",width+"px");
		}, 30);
	},
	remove:function($target){
		var $shade = $(".shade");
		if($target&&$target.size()>0){
			$shade = $target.find(".shade");
		}
		$shade.fadeOut(300);
		window.setTimeout(function(){
			$shade.remove();
			if(!!window.slidertime){
				clearInterval(slidertime);
			}
		}, 300);
	},
	run:(function($) {
		$.fn.overlay = function(options) {
			$.shade.init($(this),options);
		};
		$.fn.overlayclose = function() {
			$(this).find(".shade").fadeOut(300);
			window.setTimeout(function(){
				$(this).find(".shade").remove();
				if(!!window.slidertime){
					clearInterval(slidertime);
				}
			}, 300);
		};
	})(jQuery)
};
/*//如果上面的遮罩层不满足复杂逻辑,则可以用下面的复杂遮罩层插件.用法见下例
 $.cachedScript([CONTEXT_PATH+"/common/js/jquery.overlay.js"],function(){
	 $(".wb_m_top").overlay({
		 container: ".wb_m_top"
	  });
},false);*/

$.loadEasyUi = function(opt){
	$.cachedCss([CONTEXT_PATH+"/common/js/jquery-easyui-1.2.5/themes/gray/easyui.css",
	             CONTEXT_PATH+"/common/js/jquery-easyui-1.2.5/themes/icon.css"],function(){
		var urlArray = [CONTEXT_PATH+"/common/js/jquery-easyui-1.2.5/jquery.easyui.min.js"];
		var callback = new Function();
		if(opt){
			if(opt.urls instanceof Array){
				urlArray = urlArray.concat(opt.urls);
			}else if(typeof(opt.urls) == "string"){
				urlArray.push(opt.urls);
			}
			if(opt.callback){
				callback = opt.callback;
			}
		}
		$.cachedScript(urlArray,callback);
	});
};
var isMoney=function(obj){
   if (! obj) return false;
   return (/^\d+(\.\d{1,2})?$/).test(obj);   
}
//排序
var sort = function(dataArray,sortCode){
   	dataArray.sort(function (a, b){
            var n1 = a[sortCode];
            var n2 = b[sortCode];
            if (n1 > n2)
            {
                return 1;
            }
            else if (n1 < n2)
            {
                return -1;
            }
            else
            {
                return 0;
            }
    });
}
/*回到顶部*/
var backToTop = function(){};
$(function(){
//	var $goTopTxt = "回到顶部",
//	$goTopEle = $('<div class=gotop></div>').appendTo($("body")).append($("<span>◇</span>")).attr("title", $goTopTxt).click(function() {
//		$("html, body").animate({
//			scrollTop : 0
//		}, 500);
//	}), $goTopFun = function() {
//		var st = $(document).scrollTop(), winh = $(window).height();
//		(st > 200) ? $goTopEle.show() : $goTopEle.hide();
//		if (!window.XMLHttpRequest) {
//			$goTopEle.css("top", st + winh - 166);/*IE6下的定位*/
//		}
//	};
//	$(window).bind("scroll", $goTopFun);
});
var initForm=function(form,data){
    var $F=form;
    $F.find("input[type=text]").val("");
    $F.find("input").removeAttr('checked').removeAttr('selected');
    $F.find("select").val("");
    var key,value,tagName,type,arr;
    for(x in data){
        key = x;
        value = data[x];
        $F.find("[name='"+key+"'],[name='"+key+"[]']").each(function(){
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='INPUT'){
                if(type=='radio'){
                    $(this).attr('checked',$(this).val()==value);
                }else if(type=='checkbox'){
                    arr = value.split(',');
                    for(var i =0;i<arr.length;i++){
                        if($(this).val()==arr[i]){
                            $(this).attr('checked',true);
                            break;
                        }
                    }
                }else{
                    $(this).val(value);
                }
            }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                $(this).val(value);
            }
        });
    }
}